<template>
  <div class="system-user-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title">
            <el-icon><User /></el-icon>
            用户管理
          </span>
          <el-button 
            v-permission="'user.create'" 
            type="primary" 
            :icon="Plus" 
            @click="handleAdd"
          >
            添加用户
          </el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="searchForm.search"
          placeholder="搜索用户名、邮箱"
          style="width: 300px"
          clearable
          @clear="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
        <el-select
          v-model="searchForm.is_active"
          placeholder="用户状态"
          clearable
          style="width: 150px; margin-left: 10px"
          @change="handleSearch"
        >
          <el-option label="启用" value="true" />
          <el-option label="禁用" value="false" />
        </el-select>

        <el-select
          v-model="searchForm.is_staff"
          placeholder="用户类型"
          clearable
          style="width: 150px; margin-left: 10px"
          @change="handleSearch"
        >
          <el-option label="管理员" value="true" />
          <el-option label="普通用户" value="false" />
        </el-select>

        <el-button type="primary" :icon="Search" @click="handleSearch" style="margin-left: 10px">
          搜索
        </el-button>
        <el-button :icon="RefreshRight" @click="handleReset">重置</el-button>
      </div>

      <!-- 用户列表 -->
      <el-table 
        :data="userList" 
        v-loading="loading"
        border
        stripe
        style="margin-top: 20px"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column label="角色" min-width="120">
          <template #default="{ row }">
            <el-tag v-if="row.profile?.role_name" type="success">
              {{ row.profile.role_name }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="部门" min-width="120">
          <template #default="{ row }">
            {{ row.profile?.department || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="职位" min-width="120">
          <template #default="{ row }">
            {{ row.profile?.position || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'danger'">
              {{ row.is_active ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="类型" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.is_superuser" type="danger">超级管理员</el-tag>
            <el-tag v-else-if="row.is_staff" type="warning">管理员</el-tag>
            <el-tag v-else type="info">普通用户</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="最后登录" min-width="160">
          <template #default="{ row }">
            {{ row.last_login ? formatDate(row.last_login) : '从未登录' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="260" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-permission="'user.edit'" 
              link 
              type="primary" 
              size="small" 
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button 
              v-permission="'user.edit'" 
              link 
              type="warning" 
              size="small" 
              @click="handleResetPassword(row)"
            >
              重置密码
            </el-button>
            <el-button 
              v-permission="'user.edit'" 
              link 
              :type="row.is_active ? 'warning' : 'success'" 
              size="small" 
              @click="handleToggleStatus(row)"
            >
              {{ row.is_active ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              v-permission="'user.delete'" 
              link 
              type="danger" 
              size="small" 
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 20px; justify-content: flex-end"
        @size-change="handleSearch"
        @current-change="handleSearch"
      />
    </el-card>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" :disabled="isEdit" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="userForm.first_name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="部门">
          <el-input v-model="userForm.department" placeholder="请输入部门" />
        </el-form-item>
        <el-form-item label="职位">
          <el-input v-model="userForm.position" placeholder="请输入职位" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="userForm.role" placeholder="请选择角色" clearable style="width: 100%">
            <el-option
              v-for="role in roleList"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否启用">
          <el-switch v-model="userForm.is_active" />
        </el-form-item>
        <el-form-item label="管理员">
          <el-switch v-model="userForm.is_staff" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog
      v-model="resetPasswordDialogVisible"
      title="重置密码"
      width="400px"
      @close="handleResetPasswordDialogClose"
    >
      <el-form
        ref="resetPasswordFormRef"
        :model="resetPasswordForm"
        :rules="resetPasswordRules"
        label-width="100px"
      >
        <el-alert
          title="提示"
          type="info"
          :closable="false"
          show-icon
          style="margin-bottom: 20px"
        >
          将重置用户 <strong>{{ resetPasswordForm.username }}</strong> 的密码
        </el-alert>
        <el-form-item label="新密码" prop="password">
          <el-input
            v-model="resetPasswordForm.password"
            type="password"
            placeholder="请输入新密码"
            show-password
            clearable
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="resetPasswordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
            clearable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="resetPasswordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleResetPasswordSubmit" :loading="resetPasswordSubmitting">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, Plus, Search, RefreshRight } from '@element-plus/icons-vue'
import { getUserList, createUser, updateUser, deleteUser, toggleUserStatus, getRoleList, resetUserPassword } from '@/api/system'

// 角色列表
const roleList = ref([])

// 搜索表单
const searchForm = reactive({
  search: '',
  is_active: '',
  is_staff: ''
})

// 用户列表
const userList = ref([])
const loading = ref(false)

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('添加用户')
const isEdit = ref(false)
const submitting = ref(false)
const userFormRef = ref(null)

// 用户表单
const userForm = reactive({
  id: null,
  username: '',
  email: '',
  password: '',
  first_name: '',
  department: '',
  position: '',
  phone: '',
  role: null,
  is_active: true,
  is_staff: false
})

// 表单验证规则
const userRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

// 重置密码对话框
const resetPasswordDialogVisible = ref(false)
const resetPasswordSubmitting = ref(false)
const resetPasswordFormRef = ref(null)
const resetPasswordForm = reactive({
  userId: null,
  username: '',
  password: '',
  confirmPassword: ''
})

// 重置密码表单验证规则
const validatePasswordConfirm = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== resetPasswordForm.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const resetPasswordRules = {
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validatePasswordConfirm, trigger: 'blur' }
  ]
}

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  try {
    // 过滤掉空参数
    const params = {
      page: pagination.page,
      page_size: pagination.pageSize
    }
    
    // 只添加非空的搜索参数
    if (searchForm.search) params.search = searchForm.search
    if (searchForm.is_active) params.is_active = searchForm.is_active
    if (searchForm.is_staff) params.is_staff = searchForm.is_staff
    
    const response = await getUserList(params)
    userList.value = response.results || response
    pagination.total = response.count || 0
  } catch (error) {
    ElMessage.error('获取用户列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchUserList()
}

// 重置
const handleReset = () => {
  searchForm.search = ''
  searchForm.is_active = ''
  searchForm.is_staff = ''
  handleSearch()
}

// 添加用户
const handleAdd = () => {
  isEdit.value = false
  dialogTitle.value = '添加用户'
  Object.assign(userForm, {
    id: null,
    username: '',
    email: '',
    password: '',
    first_name: '',
    department: '',
    position: '',
    phone: '',
    is_active: true,
    is_staff: false
  })
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row) => {
  isEdit.value = true
  dialogTitle.value = '编辑用户'
  Object.assign(userForm, {
    id: row.id,
    username: row.username,
    email: row.email,
    first_name: row.first_name || '',
    department: row.profile?.department || '',
    position: row.profile?.position || '',
    phone: row.profile?.phone || '',
    role: row.profile?.role || null,
    is_active: row.is_active,
    is_staff: row.is_staff
  })
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!userFormRef.value) return
  
  await userFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    submitting.value = true
    try {
      // 准备提交数据
      const submitData = { ...userForm }
      
      // 编辑模式下，如果密码为空则删除该字段
      if (isEdit.value && !submitData.password) {
        delete submitData.password
      }
      
      // 清理数据：移除 id 字段（API不需要）
      if (isEdit.value) {
        const { id, ...updateData } = submitData
        console.log('更新用户数据:', updateData)
        await updateUser(id, updateData)
        ElMessage.success('更新用户成功')
      } else {
        console.log('创建用户数据:', submitData)
        await createUser(submitData)
        ElMessage.success('添加用户成功')
      }
      dialogVisible.value = false
      fetchUserList()
    } catch (error) {
      console.error('提交错误:', error)
    } finally {
      submitting.value = false
    }
  })
}

// 切换状态
const handleToggleStatus = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.is_active ? '禁用' : '启用'}用户 ${row.username} 吗？`,
      '提示',
      { type: 'warning' }
    )
    
    await toggleUserStatus(row.id)
    ElMessage.success('操作成功')
    fetchUserList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
      console.error(error)
    }
  }
}

// 重置密码
const handleResetPassword = (row) => {
  resetPasswordForm.userId = row.id
  resetPasswordForm.username = row.username
  resetPasswordForm.password = ''
  resetPasswordForm.confirmPassword = ''
  resetPasswordDialogVisible.value = true
}

// 提交重置密码
const handleResetPasswordSubmit = async () => {
  if (!resetPasswordFormRef.value) return
  
  await resetPasswordFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    resetPasswordSubmitting.value = true
    try {
      await resetUserPassword(resetPasswordForm.userId, resetPasswordForm.password)
      ElMessage.success('密码重置成功')
      resetPasswordDialogVisible.value = false
    } catch (error) {
      console.error('重置密码错误:', error)
    } finally {
      resetPasswordSubmitting.value = false
    }
  })
}

// 重置密码对话框关闭
const handleResetPasswordDialogClose = () => {
  if (resetPasswordFormRef.value) {
    resetPasswordFormRef.value.resetFields()
  }
}

// 删除用户
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 ${row.username} 吗？此操作不可恢复！`,
      '警告',
      { type: 'error' }
    )
    
    await deleteUser(row.id)
    ElMessage.success('删除成功')
    fetchUserList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }
}

// 对话框关闭
const handleDialogClose = () => {
  if (userFormRef.value) {
    userFormRef.value.resetFields()
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN')
}

// 挂载时获取数据
// 获取角色列表
const fetchRoleList = async () => {
  try {
    const response = await getRoleList({ page: 1, page_size: 100 })
    roleList.value = response.results || response
  } catch (error) {
    console.error('获取角色列表失败:', error)
  }
}

onMounted(() => {
  fetchUserList()
  fetchRoleList()
})
</script>

<style scoped>
.system-user-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header .title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
}

.search-bar {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px 0;
}
</style>

